package com.leyou.item.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entiey.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/category")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    /**
     * 根据id查询类别
     * @param id 分类id
     * @return 分类对象
     */
    @GetMapping("{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id){
        //根据id查询
        Category category = categoryService.getById(id);
        //转换为DTO
        CategoryDTO categoryDTO = new CategoryDTO(category);
        //封装  返回结果
//        return ResponseEntity.status(HttpStatus.OK).body(categoryDTO);
        return ResponseEntity.ok(categoryDTO);
    }

    /**
     * 根据id集合查询分类集合
     * @param ids  分类的id集合
     * @return  分类对象集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
        //根据id集合 查询
        List<Category> categoryList = categoryService.listByIds(ids);
        //转换DTO

        List<CategoryDTO> dtoList = categoryList //list<Category>
                .stream()         //stream<Category>
//                .map(category -> new CategoryDTO(category))
                .map(CategoryDTO::new)  //stream<CategoryDTO>
                .collect(Collectors.toList());  // list<Category>
/*
        List<CategoryDTO> dtoList = new ArrayList<>(categoryList.size());
        for (Category category : categoryList) {
            dtoList.add(new CategoryDTO(category));
        }
*/
        return ResponseEntity.ok(dtoList);
    }


    /**
     * 根据父分类的id  查询子分类的集合
     * @param parentId  父分类的id
     * @return  返回子分类集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid") Long parentId){
        //根据id 查询tb_category表  select * from t_category where parent_id = #{pid}
        List<Category> categoryList = categoryService.query().eq("parent_id", parentId).list();
        //转换为dto
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(categoryList);
        //返回结果
        return ResponseEntity.ok(dtoList);
    }


    /**
     * 根据品牌id，查询商品分类的集合
     * @param brandId 品牌id
     * @return  返回
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id") Long brandId){

       List<CategoryDTO> categoryDTOList =  categoryService.queryCategoryByBrandId(brandId);

       return ResponseEntity.ok(categoryDTOList);
    }
}
